//
//  MyFavoryView.swift
//  koolcar
//
//  Created by xiantian on 2023/11/9.
//

import UIKit
import MJRefresh
import SkeletonView

class MyFavoryProductView: UIView {
    var emptyView: LYEmptyView!
    var dataArray = NSMutableArray()
    var pageNo: NSInteger = 1
    var collectionView: UICollectionView!
    override init(frame: CGRect) {
        super.init(frame: frame)
        let layout = UICollectionViewFlowLayout.init()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.itemSize = CGSize.init(width: (kScreenWidth - 38)/2 , height: 210)
        self.collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: frame.size.width, height: frame.size.height), collectionViewLayout: layout)
        self.collectionView.register(GoodsCollectionViewCell.self, forCellWithReuseIdentifier: "GoodsCollectionViewCell")
        self.collectionView.register(SkeletonCollectionCell.self, forCellWithReuseIdentifier: "SkeletonCollectionCell1")
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.backgroundColor = UIColor.white
        self.collectionView.contentInset = UIEdgeInsets.init(top: 0, left: 14, bottom: 0, right: 14)
        self.collectionView.isSkeletonable = true
        self.addSubview(self.collectionView)
        
        self.setUpNoData()
        self.addPullRefreash()
        self.addLoadMoreRefreash()
    }
    
    //MARK: - 下拉刷新
    func addPullRefreash()  {
        weak var weakself = self
        let headerR = MJRefreshNormalHeader.init(refreshingBlock: {
            weakself!.fetchGetDataList(isMore: false)
        })
        headerR?.activityIndicatorViewStyle = .gray
        self.collectionView.mj_header = headerR
    }
    
    //MARK: - 上拉刷新
    func addLoadMoreRefreash()  {
        self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
            self?.pageNo = self!.pageNo + 1
            self?.fetchGetDataList(isMore: true)
        })
    }
    
    ///空视图
    func setUpNoData() {
        self.emptyView = LYEmptyView.emptyActionView(withImageStr: "icon_empty", titleStr: MMLocalizedString("no_more_data", comment: "暂时没有数据"), detailStr: "", btnTitleStr: "") {
            
        }
        emptyView?.isHidden = true
        emptyView?.subViewMargin = 28;
        emptyView?.contentViewOffset = -100
        self.collectionView.ly_emptyView = self.emptyView
    }
    
    
    ///空视图
    //    func willShowEmptyView() {
    //        if self.dataArray.count == 0 {
    //            self.collectionView.mj_footer?.isHidden = true
    //            self.emptyView.isHidden = false
    //            self.emptyView?.titleStr = MMLocalizedString("no_data", comment: "暂无数据")
    //        }else{
    //            self.emptyView.isHidden = true
    //            self.emptyView?.titleStr = ""
    //        }
    //    }
    
    public func changeFavoryProductView(){
        if self.dataArray.count > 0 {
            return
        }
        self.fetchGetDataList(isMore: false)
    }
    
    
    private func fetchGetDataList(isMore: Bool){
        let param: [String: String] = [
            "pageSize": "20",
            "pageNumber": "\(self.pageNo)"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.myFavoriteProductPage(param: param), objectType: MyFavoryResModel.self) { data in
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            let resultObj = data as! MyFavoryResModel
            if resultObj.code == "1" {
                let tempArr = resultObj.data?.content ?? []
                if self.pageNo == 1 {
                    self.dataArray.removeAllObjects()
                }
                if resultObj.data?.total ?? 0 == self.dataArray.count {
                    self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
                }
                //获取skuDTOList中的discountPrice 放到list列表中
                tempArr.forEach { item in
                    if (item.skuDTOList ?? []).count > 0 {
                        item.discountPrice = item.skuDTOList![0].discountPrice ?? 0
                    }
                }
                self.dataArray.addObjects(from: tempArr)
            }else{
                self.makeToast(message: resultObj.msg ?? "")
            }
            if self.dataArray.count < 10 {
                self.collectionView.mj_footer.isHidden = true
            }else{
                self.collectionView.mj_footer.isHidden = false
            }
            self.collectionView.reloadData()
            self.willShowSketchView()
        } error: { err in
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            self.makeToast(message: err?.domain ?? "")
        }
    }
    
    private func willShowSketchView(){
        if self.dataArray.count > 0  {
            self.emptyView.isHidden = true
        }else{
            self.emptyView.isHidden = false
        }
        self.collectionView.hideSkeleton()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


extension MyFavoryProductView: SkeletonCollectionViewDelegate, SkeletonCollectionViewDataSource {
    
    func collectionSkeletonView(_ skeletonView: UICollectionView, cellIdentifierForItemAt indexPath: IndexPath) -> SkeletonView.ReusableCellIdentifier {
        return "SkeletonCollectionCell1"
    }
    
    ///SkeletonView 1组
    func numSections(in collectionSkeletonView: UICollectionView) -> Int {
        return 1
    }
    ///SkeletonView 20个item
    func collectionSkeletonView(_ skeletonView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }
    ///SkeletonView item
    func collectionSkeletonView(_ skeletonView: UICollectionView, skeletonCellForItemAt indexPath: IndexPath) -> UICollectionViewCell? {
        let cell = skeletonView.dequeueReusableCell(withReuseIdentifier: "SkeletonCollectionCell1", for: indexPath) as! SkeletonCollectionCell
        cell.clipsToBounds = true
        return cell
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GoodsCollectionViewCell", for: indexPath) as! GoodsCollectionViewCell
        if self.dataArray.count > 0 {
            let model = self.dataArray[indexPath.row]
            cell.setStoreModel(storeModel: model as! VehicleLisetModel)
        }
        cell.collectBtn.isHidden = true
        cell.clipsToBounds = true
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard self.dataArray.count > indexPath.row else {
            return
        }
        let model = self.dataArray[indexPath.row] as! VehicleLisetModel
        let vc = ProductDetailsViewController()
        vc.id = model.id ?? 0
        self.currentViewController()?.navigationController?.pushViewController(vc, animated: true)
    }
}

